package com.changgou.user.controller;

import com.alibaba.fastjson.JSON;
import com.changgou.core.controller.AbstractCoreController;
import com.changgou.entity.BCrypt;
import com.changgou.entity.JwtUtil;
import com.changgou.entity.Result;
import com.changgou.entity.StatusCode;
import com.changgou.user.pojo.User;
import com.changgou.user.service.UserService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.http.server.reactive.ServerHttpRequest;
import org.springframework.security.access.prepost.PreAuthorize;
import org.springframework.util.StringUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.HashMap;
import java.util.Map;
import java.util.UUID;

/**
 * @author liyipeng
 * @date 2021-06-26 17:00
 */
@RestController
@RequestMapping("/user")
@CrossOrigin
public class UserController extends AbstractCoreController<User>{

    private UserService  userService;

    private final String COOKIE_NAME="Authorization";

    @Autowired
    public UserController(UserService  userService) {
        super(userService, User.class);
        this.userService = userService;
    }

    @RequestMapping(value="/login",method = {RequestMethod.GET,RequestMethod.POST})
    public Result login(String username, String password, HttpServletResponse response){
        //1.判断是否为空
        if(StringUtils.isEmpty(username) || StringUtils.isEmpty(password)){
            return new Result(false, StatusCode.LOGINERROR,"用户名和密码不能为空");
        }
        //2.判断用户信息是否存在
        User user = userService.selectByPrimaryKey(username);
        if(user==null){
            return new Result(false, StatusCode.LOGINERROR,"用户名或密码错误");
        }
        //3.判断是否密码正确
        if(!BCrypt.checkpw(password,user.getPassword())){
            return new Result(false, StatusCode.LOGINERROR,"用户名或密码错误");
        }
        //4.如果正确 返回 成功true
        //4.1 生成令牌
        Map<String,Object> subObject = new HashMap<>();
        subObject.put("username",username);
        subObject.put("role","ROLE_ADMIN");
        String token = JwtUtil.createJWT(UUID.randomUUID().toString(), JSON.toJSONString(subObject), null);
        //4.2 将令牌信息存储到cookie中
        Cookie cookie = new Cookie(COOKIE_NAME,token);
        cookie.setPath("/");
        response.addCookie(cookie);
        //4.3 将令牌信息返回给前端
        return new Result(true, StatusCode.OK,"登录成功",token);
    }

    /**
     * 获取密码
     */
    public static void main(String[] args) {
        String hashpw = BCrypt.hashpw("1234567", BCrypt.gensalt());
        System.out.println(hashpw);

    }


    //获取用户的信息
    @GetMapping("/load/{id}")
    public Result<User> loadById(@PathVariable(name="id") String id) {
        //调用UserService实现根据主键查询User
        User user =  userService.selectByPrimaryKey(id);
        return new Result<User>(true, StatusCode.OK, "查询成功", user);
    }


    @Override
    @PreAuthorize("hasAnyAuthority('admin')")
    @DeleteMapping("/{id}")
    public Result deleteById(@PathVariable(name = "id") Object id) {
        coreService.deleteById(id);
        return new Result(true, StatusCode.OK, "删除成功");
    }


    /**
     * 用户添加积分的方法
     * @param username
     * @param points 需要加的积分数
     */
    @GetMapping("/points/add")
    public Result addPoints(@RequestParam(name="username") String username,
                            @RequestParam(name="points") Integer points){
        int i = userService.addPoints(username, points);
        if(i>0){
            return new Result(true, StatusCode.OK, "添加积分成功");
        }else{
            return new Result(false, StatusCode.ERROR, "没有更新");
        }

    }



}
